import Vue from 'vue'
import App from './App.vue'
import router from './router'
import store from './store'
import axios from 'axios'

// css样式还是需要全部引入
import 'element-ui/lib/theme-chalk/index.css'
import './plugins/element'

import './static/icon/iconfont.css'

// 引入全局样式表
import './assets/css/global.css'

const http = axios.create({
  baseURL:'http://127.0.0.1:8090',
})

http.interceptors.request.use((config)=>{
  const userInfo = JSON.parse(sessionStorage.getItem('userInfo'))
  if(userInfo){
      const token = userInfo.token
      if(token){
          config.headers['authorization'] = token
      }
  }
  return config
},error=>{
  router.push('./components/Error.vue')
  return Promise.reject(error)
})

http.interceptors.response.use((response)=>{
  return response
},(error)=>{
  if(error.response.status == 401){
    Vue.prototype.$message({
      message:'还未登录哦',
      type:'warning'
    })
    store.dispatch('setShowLogin',true)
  }
  if(error.response.data.code == "10101"){
    store.dispatch('setLoggedIn',false)
    Vue.prototype.$message({
      message:'token已经过期了,请重新登录',
      type:'warning'
    })
  }
  if(error.response.data.code == '10004'){
    Vue.prototype.$message({
      message:'用户名不存在',
      type:'warning'
    })
  }
  return Promise.reject(error)
})

router.beforeEach((to,from,next)=>{
  const userInfo = JSON.parse(sessionStorage.getItem('userInfo'))
  // const isLogin = store.state.user.isLoggedIn
  if(to.meta.isAuth){
    if(userInfo){
      next()
    }else{
      store.dispatch('setShowLogin',true)
      Vue.prototype.$message({
        message:'未登录哦',
        type:'warning'
      })
      return
    }
  }
  next()
})

Vue.prototype.$http = http


new Vue({
  router,
  store,
  render: h => h(App),
  beforeCreate() {
    Vue.prototype.$bus = this
  },
}).$mount('#app')
